package com.rrqs.activity;

import android.app.AlertDialog.Builder;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import cn.jpush.android.api.JPushInterface;

import com.iflytek.cloud.Setting;
import com.litesuits.http.request.content.multi.MultipartBody;
import com.litesuits.http.request.content.multi.StringPart;
import com.rrqs.MessageEvents;
import com.rrqs.activity.data.CheckVersionData;
import com.rrqs.activity.data.ZhuanDanData;
import com.rrqs.net.AsyncHttpClient;
import com.rrqs.net.HttpResponseListener;
import com.rrqs.utils.JsonUtils;
import com.zadtek.xmqishi.R;
import com.rrqs.activity.common.Common;
import com.rrqs.activity.common.Const;
import com.rrqs.frame.MyApplication;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import static com.rrqs.activity.common.Const.TOURL;

/**
 * 设置
 *
 * @author Administrator
 */
public class SettingActivity extends BaseActivity implements OnClickListener {
    private ImageView backid;
    private TextView topview;
    private TextView set_location;
    private RelativeLayout messages, newhao, mylocation, finishs, about;
    private SharedPreferences sp; // 用户信息缓存
    private Editor editor;

    String version;

    /*
     * (non-Javadoc)
     *
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    int version_code;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting);

        MyApplication.getInstace().addActivity(this);
        PackageManager manager = this.getPackageManager();
        PackageInfo info;

        backid = (ImageView) findViewById(R.id.backid);
        topview = (TextView) findViewById(R.id.topview);
        topview.setText("设置");

        messages = (RelativeLayout) findViewById(R.id.messages);
        newhao = (RelativeLayout) findViewById(R.id.newhao);
        mylocation = (RelativeLayout) findViewById(R.id.mylocation);
        finishs = (RelativeLayout) findViewById(R.id.finishs);
        set_location = (TextView) findViewById(R.id.set_location);
        about = findViewById(R.id.about);

        backid.setOnClickListener(this);
        messages.setOnClickListener(this);
        newhao.setOnClickListener(this);
        mylocation.setOnClickListener(this);
        finishs.setOnClickListener(this);
        about.setOnClickListener(this);
        try {
            info = manager.getPackageInfo(this.getPackageName(), 0);
            version = info.versionName;
            version_code = info.versionCode;
            set_location.setText("V" + version);
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                super.handleMessage(msg);
                switch (msg.what) {
                    case Const.MSG_SET_ALIAS:// 绑定别名
                        JPushInterface.setAliasAndTags(getApplicationContext(),
                                (String) msg.obj, null, mAliasCallback);
                        break;
                }
            }
        };
    }

    @Override
    public void onClick(View arg0) {
        Intent intent;
        switch (arg0.getId()) {
            case R.id.backid:
                this.finish();
                break;
            case R.id.about:
                startActivity(new Intent(this, AboutActivity.class));

                break;

            case R.id.messages:// 管理细则
                intent = new Intent(SettingActivity.this, ManagementRules.class);
                startActivity(intent);
                break;

            case R.id.newhao:// 版本号
                showProgressDialog("正在检查新版本,请稍等...");
                updateAgent();
                break;

            case R.id.mylocation:// 我的定位
                if (Common.isNetworkConnected(SettingActivity.this)) {
                    intent = new Intent(SettingActivity.this, MyLoaction.class);
                    startActivity(intent);
                } else {
                    Common.DisplayToast(SettingActivity.this, "通信失败,请检查网络!", 1);
                }
                break;

            case R.id.finishs:// 退出
                new Builder(SettingActivity.this)
                        .setMessage("您确认要退出该账号吗?")
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog2,
                                                        int which) {
                                        // 退出,注销后将缓存中的个人信息清理
                                        sp = getSharedPreferences(Const.PREF_NAME,
                                                Context.MODE_PRIVATE);
                                        sp.edit().clear().commit();

                                        // 退出用户,将用户的uid进行别名绑定取消(退出的是当前登录的用户)
//									setAlias("");
                                        JPushInterface.setAliasAndTags(
                                                getApplicationContext(), "", null,
                                                mAliasCallback);
                                        // 退出账号将推送的通知清除
                                        JPushInterface
                                                .clearAllNotifications(getApplicationContext());
                                        // 清除自定义消息
                                        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                                        mNotificationManager.cancelAll();

                                        //停止激光服务
                                        JPushInterface.stopPush(getApplicationContext());

                                        MyApplication.getInstace().exit();

                                    }
                                }).setNegativeButton("取消", null).show();
                break;

            default:
                break;
        }
    }


    void updateAgent() {
        AsyncHttpClient httpClient = new AsyncHttpClient(com.rrqs.util.MyApplication.getInstace());

        SharedPreferences sp = com.rrqs.util.MyApplication.getInstace().getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
        String uid = sp.getString("uid", "");
        MultipartBody body = new MultipartBody();
        body.addPart(new StringPart("emp_id", uid));
        body.addPart(new StringPart("version", version_code + ""));
        body.addPart(new StringPart("ince", "check_version"));
        httpClient.post(TOURL, body, new HttpResponseListener() {
            @Override
            public void onFailure(Throwable error) {
                super.onFailure(error);
                closeProgressDialog();
            }

            @SuppressWarnings("unchecked")
            @Override
            public void onSuccess(String status, String result) {
                super.onSuccess(status, result);
                // 1表示有新版本，直接跳转到url所指向的下载页；0表示无新版本，此时需要弹窗，显示msg 的值
                closeProgressDialog();
                if ("200".equals(status)){
                    CheckVersionData data = JsonUtils.json2Class(result, CheckVersionData.class);
                    if (data.getStatus() == 0){
                        Toast.makeText(SettingActivity.this, data.getMsg(),Toast.LENGTH_SHORT).show();
                    } else  if (data.getStatus() == 1){
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.addCategory(Intent.CATEGORY_BROWSABLE);
                        intent.setData(Uri.parse(data.getUrl()));
                        startActivity(intent);

//                        startActivity(new Intent(SettingActivity.this, UpdateActivity.class).putExtra("url", data.getUrl()));
                    }
                }
            }
        });
    }

}
